<?php

namespace app\yue\home;

class Notify extends Common
{
    public function index()
    {
        $rid = input('rid/d');
        $pay = $this->getWechatPay();
        // 获取支付通知
        $notifyInfo = $pay->getNotify();

        // 支付通知数据获取失败
        if ($notifyInfo === false) {
            // 接口失败的处理
            trace($pay->errMsg, 'error');
        } else {
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                // 支付状态完全成功，可以更新订单的支付状态了
                // @todo 这里去完成你的订单状态修改操作
                $round_member = model('yue_round_member');
                if ($round_member->where(['transaction_id' => $notifyInfo['transaction_id']])->count()) {
                    $pay->replyXml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
                    return;
                }

                $member_info        = model('yue_member')->where('openId', $notifyInfo['openid'])->field('create_time, update_time, delete_time', true)->find()->toArray();
                $member_info['rid'] = $rid;
                $member_info['uid'] = $member_info['id'];
                $member_info = \array_merge($member_info, $notifyInfo);
                unset($member_info['id']);

                if ($round_member->where('rid', $rid)->count() >= 10) {
                    // 调用退款接口
                    $result = $pay->refund($notifyInfo['out_trade_no'], $notifyInfo['transaction_id'], self::getBillno(), $notifyInfo['total_fee'], $notifyInfo['total_fee']);
                    // $result = $pay->transfers($notifyInfo['openid'], $notifyInfo['cash_fee'], $notifyInfo['out_trade_no'], '人数已满，退款通知');
                    $member_info['status'] = 0;
                    $round_member->save($member_info);
                    return;
                }

                $round_member->save($member_info);

                $this->chkResult($rid);

                // 回复xml，replyXml方法是终态方法
                $pay->replyXml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
            }
        }

    }

}
